package com.xexun.gpstracker.study;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.*;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;
import com.xexun.gpstracker.base.BaseActivity;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.CommonRestPath;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.dialog.WizardAlertDialog;
import com.xexun.gpstracker.inter.HttpCallback;
import com.xexun.gpstracker.pojo.ResponseData;
import com.xexun.gpstracker.util.HttpUtil;
import com.xexun.gpstracker.util.JsonHttpResponseHelper;
import com.xexun.gpstracker.vo.GTLatLng;
import com.xexun.gpstracker.vo.Session;
import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TakePhotoActivity extends BaseActivity {
    public static final int REQUEST_CAMERA = 1;
    private String mFilePath;
    private Context mContext;
    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        mContext = this;

        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            Log.v("TestFile", "SD card is not avaiable/writeable right now.");
            finish();
            return;
        }

        String fileDir = Environment.getExternalStorageDirectory().getPath();
        fileDir = fileDir + "/SWIMG/";
        File file = new File(fileDir);
        file.mkdirs();// 创建文件夹

        // Check permission for CAMERA
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // Check Permissions Now
            // Callback onRequestPermissionsResult interceptado na Activity TakePhotoActivity
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    TakePhotoActivity.REQUEST_CAMERA);
        } else {
            // permission has been granted, continue as usual
            takePhoto();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == TakePhotoActivity.REQUEST_CAMERA) {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                //Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
                takePhoto();
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                //Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    public void takePhoto() {
        mFilePath = Environment.getExternalStorageDirectory().getPath();
        mFilePath = mFilePath + "/SWIMG/";
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String name = fmt.format(new Date()) + ".jpg";
        mFilePath = mFilePath + name;
        Uri uri = Uri.fromFile(new File(mFilePath));

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            String oriFile = mFilePath;
            createWaterMaskImage();
            File file = new File(oriFile);
            if(file.exists()) {
                file.delete();
            }
            submitWaterMaskImage(mFilePath);
            finish();
        } else if(resultCode == Activity.RESULT_CANCELED) {
            takePhoto();
        }
    }

    void createWaterMaskImage() {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = fmt.format(new Date());

        //Bitmap photo = BitmapFactory.decodeFile(mFilePath);
        Bitmap photo = null;
        try {
            InputStream is = new FileInputStream(mFilePath);
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inTempStorage = new byte[200 * 1024];
            opts.inPreferredConfig = Bitmap.Config.RGB_565;
            opts.inPurgeable = true;
            opts.inSampleSize = 4;
            opts.inInputShareable = true;
            photo = BitmapFactory.decodeStream(is, null, opts);
        } catch (FileNotFoundException e) {

        }

        int width = photo.getWidth(), hight = photo.getHeight();

        Bitmap icon = Bitmap.createBitmap(width, hight, Bitmap.Config.RGB_565);//建立一个空的BItMap
        Canvas canvas = new Canvas(icon);//初始化画布 绘制的图像到icon上

        Paint photoPaint = new Paint(); //建立画笔
        photoPaint.setDither(true); //获取跟清晰的图像采样
        photoPaint.setFilterBitmap(true);//过滤一些

        Rect src = new Rect(0, 0, width, hight);//创建一个指定的新矩形的坐标
        Rect dst = new Rect(0, 0, width, hight);//创建一个指定的新矩形的坐标
        canvas.drawBitmap(photo, src, dst, photoPaint);//将photo 缩放或则扩大到 dst使用的填充区photoPaint

        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);//设置画笔
        textPaint.setTextSize(width/10);//字体大小
        textPaint.setStrokeWidth(3);
        textPaint.setTypeface(Typeface.DEFAULT_BOLD);//采用默认的宽度
        textPaint.setColor(Color.RED);//采用的颜色
        textPaint.setTextAlign(Paint.Align.LEFT);
        Rect bounds = new Rect();
        textPaint.getTextBounds(time, 0, time.length(), bounds);
        Paint.FontMetricsInt fontMetrics = textPaint.getFontMetricsInt();
        int baseline = (hight - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
        canvas.drawText(time,width/2 - bounds.width()/2, baseline, textPaint);

        //canvas.drawText(time, 20, 26, textPaint);//绘制上去 字，开始未知x,y采用那只笔绘制
        canvas.save();
        canvas.restore();

        FileOutputStream fos = null;
        try {
            mFilePath = Environment.getExternalStorageDirectory().getPath();
            mFilePath = mFilePath + "/SWIMG/";
            mFilePath = mFilePath + time + ".jpg";
            fos = new FileOutputStream(mFilePath);
            //fos = openFileOutput(time + ".jpg", Context.MODE_PRIVATE);
            icon.compress(Bitmap.CompressFormat.JPEG, 70, fos);
        } catch (FileNotFoundException e) {

        } finally {
            photo.recycle();
            photo = null;
            icon.recycle();
            icon = null;
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 发送水印图片
     */
    public void submitWaterMaskImage(String filePath) {
        String url=Constants.baseUrl + CommonRestPath.attendanceUpload();
        Map<String,Object> params=new HashMap<String,Object>();

        File file = new File(filePath);
        params.put("file", file);
        Date date = new Date();
        params.put("triggerTime", date.getTime()+"");
        GTLatLng latLng = Session.getInstance().getLatLng();
        params.put("latitude", latLng.getLatitude()+"");
        params.put("longitude", latLng.getLongitude()+"");
        params.put("imei", Session.getInstance().getClientId());

        HttpCallback callback = new HttpCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onSuccess(ResponseData obj) throws Exception {
                String oriFile = mFilePath;
                File file = new File(oriFile);
                if(file.exists()) {
                    file.delete();
                }
                if (obj.getRetcode() == 1) {
                    Toast.makeText(mContext, R.string.atdsuccess, Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(mContext, R.string.atdfail, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(String message) throws Exception {
                String oriFile = mFilePath;
                File file = new File(oriFile);
                if(file.exists()) {
                    file.delete();
                }
                Toast.makeText(mContext, R.string.atdfail, Toast.LENGTH_LONG).show();
            }
        };

        HttpUtil.postMulti(url,params,new JsonHttpResponseHelper(callback).getHandler());
    }
}